package com.un.ebs.core.exception;

import com.un.ebs.core.exception.*;
import com.un.ebs.core.util.DateUtils;
import com.un.ebs.core.util.WebResult;
import com.un.ebs.core.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Set;

/**
 * @email 496382223@qq.com
 * @author:Lijj
 * @date: 2019/7/24
 */
@ControllerAdvice
public class ExceptionHandle {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = SystemException.class)
    @ResponseBody
    public WebResult Handle(SystemException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        writeException(e);
        return WebUtils.error(-2, e.getMessage(), null);
    }

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public WebResult Handle(RuntimeException e){
        logger.error(e.getMessage());
        e.printStackTrace();
        writeException(e);
        return WebUtils.error(-3,e.getMessage(),null);
    }

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public WebResult HandleBaseException(BaseException e){
        logger.error(e.getMessage());
        e.printStackTrace();
        writeException(e);
        return WebUtils.error(e.getCode(),e.getMessage(),null);
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public WebResult Handle(Exception e){
        logger.error(e.getMessage());
        e.printStackTrace();
        writeException(e);
        return WebUtils.error(-2,e.getMessage(),null);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public WebResult methodArgNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage());
        StringBuilder errMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(ex -> errMsg.append(ex.getDefaultMessage() + "<br>"));
        writeException(e);
        return WebUtils.error(-1,errMsg.toString());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public WebResult methodArgNotValidException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> cves = e.getConstraintViolations();
        StringBuffer errMsg = new StringBuffer();
        cves.forEach(ex -> errMsg.append(ex.getMessage()));
        logger.error(errMsg.toString());
        writeException(e);
        return WebUtils.error(-1, errMsg.toString());
    }

    private void writeException(Exception e) {

        File file = new File("log//err//" + DateUtils.formatDate(new Date(), "yyyyMMdd") + "//" + System.currentTimeMillis() + ".txt");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException ex) {
                System.out.println("日志文件创建失败：" + ex.getMessage());
            }
        }

        PrintWriter pw = null;
        try {
            pw = new PrintWriter(file);
            e.printStackTrace(pw);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

        if (pw != null) {
            pw.flush();
            pw.close();
        }

    }
}
